<!--
- File:    添加心情日志.
-->
<template>
  <div class="Web_Box">
    <div class="bg_fff">
      <div class="edittext">
        <textarea placeholder="添加文字" v-model="content"></textarea>
        <div class="fll_price2 f-cb">
          <div class="fllimg">
            <div id="select-pic">
              <input type="file" id="fileInput1" accept="image/jpeg,image/jpg,image/png,image/gif" style="display: none" @change="fileSelected">
            </div>
            <i class="iconfont icon-tianjia1" @click="getImg" style="pointer-events: auto"></i>
          </div>
          <div class="fllimg" v-for="(img, imgIndex) in imgList" @click="delImg(imgIndex)">
            <img :src="$config.imgsite + $config.uploadImgSrc + img + '_w200'">
          </div>
        </div>
      </div>
      <div>
        <div class="s_title" style="border-top: 1px #eee solid; border-bottom: none"><span style="margin-left: 0.5rem">类型</span></div>
        <div class="screen_b">
          <ul class="f-cb">
            <li v-for="tag in diaryTagList" :class="{'tag-on': tagIsSelected(tag.d_id)}" @click="switchSelectTag(tag.d_id)">{{tag.d_name}}</li>
          </ul>
        </div>
      </div>
    </div>
    <!--<div class="Fill_input f-cb" style="margin: .5rem 0 0 0; background: #fff;">-->
    <!--<i class="iconfont icon-triangle"></i>-->
    <!--<label>类型-->
    <!--<select name="type" v-model="tagSelectedList">-->
    <!--<option value="" selected>请选择</option>-->
    <!--<option :value="classify.d_id" v-for="classify in diaryTagList">{{classify.d_name}}</option>-->
    <!--</select></label>-->
    <!--</div>-->
    <!--<div class="buttonfinish" @click="addDiary"><a>发布</a></div>-->
    <div class="artic_btn f-cb">
      <a class=" bg_a8a8a8" @click="back">取消</a><a class="bg_3dbb6e" @click="addDiary">发布</a>
    </div>
    <mt-actionsheet
      :actions="actions"
      v-model="sheetVisible">
    </mt-actionsheet>
  </div>
</template>

<script>
  import {Actionsheet, DatetimePicker} from 'mint-ui'
  import * as request from '../../../request'

  export default{
    data() {
      return {
        plantId: this.$route.query.plant,
        content: '',
        imgList: [],
        diaryTagList: [],
        tagSelectedList: [],
        sheetVisible: false,
        actions: [{
          name: '拍照',
          method: this.getFromCamera
        }, {
          name: '从相册选取',
          method: this.getFromAlbum
        }],
        currentDate: new Date()
      }
    },
    components: {
      'mt-actionsheet': Actionsheet,
      'mtDatetimePicker': DatetimePicker
    },
    beforeRouteEnter (to, from, next) {
      request.getDiaryClassify().then(data => {
        next(vm => {
          vm.diaryTagList = data
        })
      }).catch(e => {
        next()
      })
    },
    beforeRouteLeave  (to, from, next) {
      this.$indicator.close()
      next()
    },
    created() {
      // this.$native.weixinShare(window.location.href)
    },
    mounted() {
      this.$native.weixinShare(window.location.href, '遇花园', null, '')
    },
    methods: {
      back() {
        this.$router.go(-1)
      },
      switchSelectTag(tagId) {
        let index = this.tagSelectedList.indexOf(tagId)
        if (index == -1) {
          this.tagSelectedList.push(tagId)
        } else {
          this.tagSelectedList.splice(index, 1)
        }
      },
      tagIsSelected(tagId) {
        if (this.tagSelectedList.indexOf(tagId) != -1) {
          return true
        } else {
          return false
        }
      },
      addDiary() {
        if (this.content == '' && this.imgList.length == 0) {
          this.$toast('请添加文字或图片')
          return
        }
        if (this.tagSelectedList.length <= 0) {
          this.$toast('请选择类型')
          return
        }
        this.$request.addDiary(this.tagSelectedList, this.content, this.imgList).then(data => {
          this.$toast('发布成功')
          this.$router.go(-1)
        }).catch(e => {
          this.$toast('发布失败:' + e.msg)
        })
      },
      getImg() {
        if (this.imgList.length >= 9) {
          this.$toast('只能选择9张图片~')
          return
        }
        let deviceType = this.$utils.getDeviceType()
        if (deviceType == 'wx-iPhone' || deviceType == 'wx-Android') {
          let wxImgPromiseList = []
          wx.chooseImage({ // eslint-disable-line
            count: 9 - this.imgList.length, // 默认9
            sizeType: ['original', 'compressed'], // 可以指定是原图还是压缩图，默认二者都有
            sourceType: ['album', 'camera'], // 可以指定来源是相册还是相机，默认二者都有
            success: (res) => {
              for (let i = 0; i < res.localIds.length; i++) {
                var localId = res.localIds[i]
                let promise = this.$utils.wxGetLocalImgData(localId)
                wxImgPromiseList.push(promise)
              }
              Promise.all(wxImgPromiseList).then((imgList) => {
                this.$indicator.open('上传图片中...')
                this.$request.uploadImg(imgList).then(data => {
                  this.imgList = [...this.imgList, ...data]
                }).catch(e => {
                  this.$toast('上传图片失败:' + e.msg)
                }).finally(() => {
                  this.$indicator.close()
                })
              })
            }
          })
        } else if (deviceType == 'iPhone') {
          this.getFromAlbum() // 因为iphone不带capture属性的input 点击后本身就会弹出选择图库或拍照
        } else {
          this.sheetVisible = true
        }
      },
      delImg(index) {
        this.$messageBox.confirm('确定删除图片?').then(action => {
          this.imgList.splice(index, 1)
        }).catch(() => {
        })
      },
      getFromCamera() {
        var imgInputFile = document.getElementById('fileInput1')
        if (!imgInputFile.hasAttribute('capture')) {
          imgInputFile.setAttribute('capture', 'camera')
        }
        this.$utils.clickFileInput(imgInputFile)
      },
      getFromAlbum() {
        var imgInputFile = document.getElementById('fileInput1')
        if (imgInputFile.hasAttribute('capture')) {
          imgInputFile.removeAttribute('capture')
        }
        this.$utils.clickFileInput(imgInputFile)
      },
      clearInputFile() {
        var self = this
        var selectPic = document.getElementById('select-pic')
        var randomStr = Math.random().toString(36)
        selectPic.innerHTML = '<input id="fileInput1" type="file" title="" ' + randomStr + '"  accept="image/jpeg,image/jpg,image/png,image/gif"  id="fileInput1" style="visibility: hidden" >'
        document.getElementById('fileInput1').addEventListener('change', self.fileSelected)
      },
      fileSelected(e) {
        try {
          var reader = new window.FileReader()
          reader.onload = (e) => {
            if (e.total > 1024 * 1024 * 5) {
              this.$toast('图片大小不能超过5M')
              return
            }
            // 调用图片压缩方法
            // console.log("成功加载图片，开始压缩图片...")
            this.$utils.compress(e.target.result, (imgDataUrl) => {
              // todo 调用上传图片接口
              this.$indicator.open('上传图片中...')
              this.$request.uploadImg(imgDataUrl).then(data => {
                this.imgList.push(data[0])
              }).catch(e => {
                this.$toast('上传图片失败:' + e.msg)
              }).finally(() => {
                this.$indicator.close()
              })
            })
          }
          // 选取同名文件不会再次触发change事件，所以在加载后替换input控件
          reader.onloadend = (e) => {
            this.clearInputFile()
          }
          reader.readAsDataURL(e.target.files[0])
        } catch (e) {
          console.log('读取图片文件发生了错误')
          console.log(e)
        }
      }
    }
  }
</script>

<style>
  .tag-on {
    background-color: #3dbb6e !important;
    color: #fff !important;
  }
</style>
